/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.cesupa.cabcc.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import org.richfaces.model.UploadItem;

/**
 *
 * @author yuri
 */
public class FileUpload {

    private UploadItem uploadedFile;
    private final static String ROOT = "/var/www/img" + File.separator + "fotos" + File.separator;


    static {
        File root = new File(ROOT);
        if (!root.exists()) {
            root.mkdirs();
        }
        System.out.println(root.getAbsolutePath());
    }

    public FileUpload() {
    }

    public String salvarArquivo() throws IOException {
        if (uploadedFile != null) {
            //criacao de um arquivo vazio no servidor
            File arquivoServidor = new File(ROOT + UUID.randomUUID() + ".png");

            //salva o arquivo no servidor
            BufferedOutputStream os = null;
            FileInputStream is = null;
            try {
                is = new FileInputStream(uploadedFile.getFile());
                os = new BufferedOutputStream(new FileOutputStream(arquivoServidor));
                int count = 0;
                while ((count = is.read()) != -1) {
                    os.write(count);
                }
                os.flush();
            } finally {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            }
            return arquivoServidor.getAbsolutePath();
        }
        return null;
    }

    // … setter and getter …
    public UploadItem getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadItem uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
}